package com.ixoko.swagger.controller.client;

import com.alibaba.fastjson.JSONObject;
import com.ixoko.swagger.dto.BaseResDto;
import com.ixoko.swagger.util.Base64Util;
import com.ixoko.swagger.util.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

/**
 * @author luojie
 * @Date 2018/7/1
 */
@Api(description = "客户端控制器")
@RestController
@RequestMapping("/tourism/client")
public class ClientController {

    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${http.client.base.url}")
    private String baseUrl;

    @ApiOperation(value = "刷新token按钮", httpMethod = "GET")
    @RequestMapping("/refresh")
    public BaseResDto<Object> refresh(String mobile, String password) throws IOException, ExecutionException {

        BaseResDto<Object> resDto = new BaseResDto<>();

        String tokenUrl = baseUrl + "/public/getToken";
        String post = HttpClientUtil.post(tokenUrl, "{\"id\":\"2121\",\"platform\":\"1\",\"deviceId\":\"1234567uytrs\"}");
        String token = JSONObject.parseObject(post).getString("data");

        if (StringUtils.isBlank(token)) {
            resDto.setFlag(false);
            resDto.setError("0000000", JSONObject.parseObject(post).getString("errorMsg"));
            return resDto;
        }

        String loginUrl = baseUrl + "/client/login";
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("token", token);

        HashMap<String, String> bodyMap = new HashMap<>();
        bodyMap.put("mobile", mobile);
        bodyMap.put("cert", Base64Util.encode(password.getBytes()));
        bodyMap.put("loginType", "1");

        String loginPost = HttpClientUtil.post(loginUrl, JSONObject.toJSONString(bodyMap), headerMap);
        String loginToken = JSONObject.parseObject(JSONObject.parseObject(loginPost).getString("data")).getString("loginToken");

        HttpClientUtil.TOKEN = loginToken;

        resDto.setFlag(true);
        resDto.setError("0000000", "刷新成功 loginToken=" + loginToken);
        return resDto;
    }
}
